import java.io.*;
import java.net.*;
import java.util.*;
//TODO:esperar a que acabe el script.
public class MF_ConnectionProcessor implements Runnable
{
  private MF_Server server;

  private Socket socket;

  private DataInputStream din;

  private DataOutputStream dout;

  private static String EM_URL = "localhost";
  
  public MF_ConnectionProcessor( MF_Server server, Socket socket ) {
    this.server = server;
    this.socket = socket;

    new Thread( this ).start();
  }
  
  public void run() {
    try {
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );

      String id = Integer.toString(din.readInt());
      System.out.println("Se procesará el archivo con ID "+id);
      FileWriter fstream = new FileWriter(id+".dat");
      BufferedWriter bout = new BufferedWriter(fstream);
      String dades = din.readUTF();
      while (!dades.equals("Fin!")){
	bout.write(dades);
	bout.newLine();
	dades = din.readUTF();
      }
      bout.close();//!!!!!!!!!!!!!!
      
      //Lanzamiento del script que realiza el experimento.
      List<String> command = new ArrayList<String>();
      
      command.add("sh");
      command.add("pmainframe.sh");
      command.add(id);                            //idExperiment
      command.add(id+".dat");                     //inFile
      command.add(".");                           //outputDir
      command.add("11");                          //operationMask
      
      // Create and execute the new process 
      ProcessBuilder builder = new ProcessBuilder(command);
      //Redirects stderror to stdout
      builder.redirectErrorStream(true);
      Process process = builder.start();
      
      String s = null;
      // Redirigimos la salida estándar:
      BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(process.getInputStream()));
      BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(process.getErrorStream()));
      System.out.println("Here is the standard output of the command:\n");
      while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
      }
      System.out.println("Here is the standard error of the command (if any):\n");
      while ((s = stdError.readLine()) != null) {
        System.out.println(s);
      }
      int exit = process.waitFor(); //Nos esperamos a que acabe.*/

      new MF_Client(EM_URL,3333,id);

      try {
        socket.close();
      } catch( IOException ie2 ) {
        System.out.println( "Error closing socket "+socket );
      }

      server.removeConnection( this );

      System.out.println( "Closed connection from socket "+socket );
    }
    catch (Exception e){e.printStackTrace();}
  }

}
